<cfscript>
component extends="DynamoDBObject" {

	function init(access, table) {
		variables.access = access;
		variables.table = table;
		super.init();
		return this;
	}

	boolean function exists() {
		try {
			describe();
		} catch(any e) {
			if (e.errorCode eq "ResourceNotFoundException") return false;
			else throw(object:e);
		}
		return true;
	}

	function itemCount() {
		return describe().itemCount;
	}
	
	function create(string hashKeyName, string hashKeyType, numeric writeCapacity, numeric readCapacity) {
		local.hashKeyElement = _jobj("com.amazonaws.services.dynamodb.model.KeySchemaElement").withAttributeName(hashKeyName).withAttributeType(hashKeyType);
		local.keySchema = _jobj("com.amazonaws.services.dynamodb.model.KeySchema").init(local.hashKeyElement);
		local.throughput = _jobj("com.amazonaws.services.dynamodb.model.ProvisionedThroughput").withWriteCapacityUnits(JavaCast("long", writeCapacity)).withReadCapacityUnits(JavaCast("long", readCapacity));
		local.request = _jobj("com.amazonaws.services.dynamodb.model.CreateTableRequest").init(variables.table, local.keySchema).withProvisionedThroughput(local.throughput);
		local.result = variables.access.doSync("createTable", local.request);
		return local.result;
	}

	function describe() {
		local.request = _jobj("com.amazonaws.services.dynamodb.model.DescribeTableRequest").withTableName(variables.table);
		local.result = variables.access.doSync("describeTable", local.request).getTable();
		local.meta = {creationDateTime:local.result.getCreationDateTime(), 
					  itemCount:local.result.getItemCount(),
					  keySchema:local.result.getKeySchema(),
					  provisionedThroughput:local.result.getProvisionedThroughput(),
					  tableName:local.result.getTableName(),
					  tableSizeBytes:local.result.getTableSizeBytes(),
					  tableStatus:local.result.getTableStatus()};
		return local.meta;
	}
	
	function delete(boolean force=false) {
		if (!force and itemCount()) throw(type="Application", message="To delete a table which contains data, use delete(true)");
		local.request = _jobj("com.amazonaws.services.dynamodb.model.DeleteTableRequest").init(variables.table);
		variables.access.doSync("deleteTable", local.request);
	}

/*
	function serializeToFile(path, boolean overwrite=false) {
		var qry = select().limit(2500);
		var file = FileOpen(path, overwrite?"write":"append");
		FileWrite(file, "[");
		while (qry.hasmore()) {
			var result = qry.execute();
			loop from="1" to="#ArrayLen(result)#" index="local.i" {
				if (local.i gt 1) FileWrite(file, ",");
				FileWriteLine(file, SerializeJson(result[local.i].toMemento().data));
			}
		}
		FileWrite(file, "]");
		FileClose(file);
	}
*/
	// Factories 
	
	function item(required Value hashKey) {
		return new HashItem(variables.access, variables.table, hashKey);
	}
/*	
	function select() {
		return new Select(variables.access).domain(variables.domain);
	}
	*/
}
</cfscript>